/**     
* @Title: MyCustomUserService.java   
* @Package me.springboot.security.userdetails   
* @Description: TODO   
* @author xaoyaoyao
* @date 2017年8月25日 下午10:43:47
*/
package me.springboot.security.userdetails;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import me.springboot.security.MyGrantedAuthority;
import me.springboot.security.model.Resource;
import me.springboot.security.service.ResourceService;
import me.springboot.security.service.UserService;

/**
 * @ClassName: MyCustomUserService
 * @Description: TODO
 * @author xaoyaoyao
 * @date 2017年8月25日 下午10:43:47
 * 
 */
@Service
public class MyCustomUserService implements UserDetailsService {

	@javax.annotation.Resource
	private UserService userService;

	@javax.annotation.Resource
	private ResourceService resourceService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		MyUserDetails user = userService.queryByUsername(username);
		if (null != user) {
			List<Resource> resources = resourceService.findByUserId(user.getId());
			List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
			if (!CollectionUtils.isEmpty(resources)) {
				for (Resource res : resources) {
					GrantedAuthority grantedAuthority = new MyGrantedAuthority(res.getUri(), res.getMethod());
					grantedAuthorities.add(grantedAuthority);
				}
				user.setAuthorities(grantedAuthorities);
				return user;
			}
		}
		throw new UsernameNotFoundException("USERNAME: " + username + " DO NOT EXIST!");
	}
}
